<?php
// +----------------------------------------------------------------------
// | 后台函数库
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: common.php 115 2011-05-11 09:06:41Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


if (!defined('IN_BLOG')) {
    die('Hacking attempt');
}

require_cache (ROOT_PATH.'Includes/common.inc.php');

/**
 * 记录后台操作日志
 *
 * @access  public
 * @param   string      $log_info      日志内容
 * @param   string      $log_script    页面
 * @return  void
 */
function set_log($log_info,$log_script = __ACTION__) {
	$user_id   =  $_SESSION[C('USER_AUTH_KEY')];
   	$log_ip    =  get_client_ip();
	$log_time  =  time();
	$log	   =  M('AdminLog');
	$data      =  array();
	$data['user_id']	   =	$user_id;
	$data['log_time']	   =	$log_time;
	$data['log_info']      =	$log_info;
	$data['log_script']	   =	$log_script;
	$data['log_ip']	       =	$log_ip;
	$log->add($data);
}

/**
 * 文件或目录权限检查函数(from ecshop
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15}，每个值表示的含义可由四位二进制数组合推出。
 *                          返回值在二进制计数法中，四位由高到低分别代表
 *                          可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path) {
    /* 如果不存在，则不可读、不可写、不可改 */
    if (!file_exists($file_path)) {
        return false;
    }

    $mark = 0;

    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';

        /* 如果是目录 */
        if (is_dir($file_path)) {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false) {
                return $mark; //如果目录打开失败，直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false) {
                $mark ^= 1; //目录可读 001，目录不可读 000
            }
            @closedir($dir);

            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false) {
                return $mark; //如果目录中的文件创建失败，返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false) {
                $mark ^= 2; //目录可写可读011，目录可写不可读 010
            }
            @fclose($fp);

            @unlink($test_file);

            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false) {
                return $mark;
            }
            if (@fwrite($fp, "modify test.\r\n") !== false) {
                $mark ^= 4;
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false) {
                $mark ^= 8;
            }
            @unlink($test_file);
        } elseif (is_file($file_path)) {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp) {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);

            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false) {
                $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false) {
                $mark ^= 8;
            }
        }
    } else {
        if (@is_readable($file_path)) {
            $mark ^= 1;
        }

        if (@is_writable($file_path)) {
            $mark ^= 14;
        }
    }

    return $mark;
}

/**
 *  返回一个随机的名字
 *
 * @return  string      $str    随机名称
*/
function get_random_name() {
	$str = date('Ymd');
	for ($i = 0; $i < 6; $i++) {
		$str .= chr(mt_rand(97, 122));
	}
	return $str;
}

/**
 *  将含有单位的数字转成字节(from ecshop
 *
 * @access  public
 * @param   string      $val        带单位的数字
 *
 * @return  int         $val
 */
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

/**
 * 将字节转成可阅读格式(from ecshop
 *
 * @access  public
 * @param
 *
 * @return void
 */
function num_bitunit($num) {
    $bitunit = array(' B',' KB',' MB',' GB');
    for ($key = 0, $count = count($bitunit); $key < $count; $key++) {
       if ($num >= pow(2, 10 * $key) - 1) {// 1024B 会显示为 1KB
           $num_bitunit_str = (ceil($num / pow(2, 10 * $key) * 100) / 100) . " $bitunit[$key]";
       }
    }
    return $num_bitunit_str;
}

/**
 * 过滤备份数据中的'--'(from ecshop
 *
 * @access  public
 * @param
 * @return  void
 */
function remove_comment($var) {
	return (substr($var, 0, 2) != '--');
}

/**
 * 清除模版编译文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_compiled_files($ext = '') {
    return clear_tpl_files(false, $ext);
}

/**
 * 清除缓存文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_cache_files($ext = '') {
    return clear_tpl_files(true, $ext);
}

/**
 * 清除模版编译和缓存文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名后缀
 * @return  void
 */
function clear_all_files($ext = '') {
    return clear_tpl_files(false, $ext) + clear_tpl_files(true,  $ext);
}

/**
 *  清除指定后缀的模板缓存或编译文件(from ecshop
 *
 * @access  public
 * @param  bool       $is_cache  是否清除缓存还是清出编译文件
 * @param  string     $ext       需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_tpl_files($is_cache = true, $ext = '') {

    $dirs = array();
	
	//文件目录
	$tmp_dir = ROOT_PATH . STATIC_CACHES_DIR;
	$compiled_dir = ROOT_PATH . 'Blog/Runtime/Cache/';
	$compiled_admin_dir = ROOT_PATH . 'Admin/Runtime/Cache/';

    if ($is_cache) {
        $dirs[] = $tmp_dir;
    } else {
        $dirs[] = $compiled_dir;
        $dirs[] = $compiled_admin_dir;
    }

    $str_len = strlen($ext);
    $count   = 0;

    foreach ($dirs as $dir) {
        $folder = @opendir($dir);

        if ($folder === false) {
            continue;
        }

        while ($file = readdir($folder)) {
            if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html' || $file == 'index.php') {
                continue;
            }
            if (is_file($dir . $file)) {
                /* 如果有文件名则判断是否匹配 */
                $pos = ($is_cache) ? strrpos($file, '_') : strrpos($file, '.');

                if ($str_len > 0 && $pos !== false) {
                    $ext_str = substr($file, 0, $pos);

                    if ($ext_str == $ext) {
                        if (@unlink($dir . $file)) {
                            $count++;
                        }
                    }
                } else {
                    if (@unlink($dir . $file)) {
                        $count++;
                    }
                }
            }
        }
        closedir($folder);
    }

    return $count;
}

/**
 * 判断字符串是否汉字
 *
 * @access     public
 * @param      string  $str   字符串
 *
 * @return     bool
 *
 */
function is_gb($str) {      
	if (strlen($str)>=2) {      
		$str=strtok($str,"");      
		if ((ord($str[0])<161)||(ord($str[0])>247)) {      
			return false;      
		} else {      
			if ((ord($str[1])<161)||(ord($str[1])>254)) {      
				return false;      
			} else {      
				return true;      
			}      
		}      
	} else {      
		return false;   
	}      
} 

/**
 * 创建静态缓存文件(后台)
 *
 * @access  public
 * @return  void
 */
function create_static_caches() {
	$path  =  ROOT_PATH . STATIC_CACHES_DIR;
	//日历
	if (!file_exists($path.'calendar_static.php')) {
		$cal   = $path.'calendar_static.php';
		import("@.ORG.Calendar");
		$y = Calendar::local_date('Y');
		$m = Calendar::local_date('m');	
		$date = new Calendar($y,$m);
		$start_time = local_mktime(0,0,0,$m,1,$y);
		$end_time   = local_mktime(0,0,0,$date->nextMonth,1,$date->nextYear);
		$num  = get_posts_from_date($start_time,$end_time);
		$html = $date->outPut($num);	
		if($fp = @fopen($cal, 'wb')) {
			$cachedata = "\$html = unserialize('".addcslashes(serialize($html), '\\\'')."');";
			@fwrite($fp, "<?php\n//nblog cache file\n//Created on " . date('Y-m-d H:i:s',time()) . "\n\nif (!defined('IN_BLOG')) exit('Hacking attempt');\n\n\$expiration='".(time() + 600)."';\r\n".$cachedata."\r\n?>");
			@fclose($fp);
			@chmod($cal, 0777);
		}
	}
	//日志分类
	if (!file_exists($path.'category_static.php')) {
		$cat  = D('Category');
		$data = $cat->getCatArray();
		f_static_cache('category_static',$data ,$path); 
	}
	//过滤和排序所有日志分类，返回一个带有缩进级别的数组
	if (!file_exists($path.'cat_option_static.php')) {
		$cat  = D('Category');
		$data = f_static_cache('category_static','',$path);
		$data = $cat->getCatOptions($data,$cat_id);
		f_static_cache('cat_option_static',$data ,$path); 
	}
	//隐藏不可显示的分类,经过过滤和排序处理,带有缩进级别的数组
	if (!file_exists($path.'category_isshow_static.php')) {
		$cat  = D('Category');
		$data = $cat->getCatList(0,0,0,false,false);
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k!='category_id'&&$k!='category_url'&&$k!='category_title'&&$k!='posts_num'&&$k!='level') {
					unset($data[$key][$k]);
				}
			}
		}
		f_static_cache('category_isshow_static',$data ,$path); 
	}
	//友情链接
	if (!file_exists($path.'links_static.php')) {
		$links = M('Links');
		$map = array();
		$map['link_status'] = 1; 
		$map['link_visible'] = 1;
		$data = $links->field('link_url,link_name,link_description')->where($map)->order('link_sort asc')->limit(C('links_num'))->findAll();
		f_static_cache('links_static',$data ,$path); 		
	}
	//最新评论	
	if (!file_exists($path.'comment_static.php')) {
		$com = M('Comment');
		$map = array();
		$map[C('DB_PREFIX').'comment.comment_status'] = 1; 
		$map[C('DB_PREFIX').'comment.comment_visible'] = 1;
		$map[C('DB_PREFIX').'comment.comment_type'] = array('neq',2);
		$map[C('DB_PREFIX').'posts.posts_status'] = 1;
		if (C('remark')) {
			$map[C('DB_PREFIX').'comment.comment_remark'] = 1;
		}
		$data = $com->where($map)->field(C('DB_PREFIX').'comment.comment_id,'.C('DB_PREFIX').'comment.posts_id,'.C('DB_PREFIX').'posts.posts_title,'.C('DB_PREFIX').'posts.posts_url,'.C('DB_PREFIX').'comment.comment_content,'.C('DB_PREFIX').'comment.comment_author,'.C('DB_PREFIX').'comment.comment_email,'.C('DB_PREFIX').'comment.comment_url')->join(C('DB_PREFIX').'posts ON '.C('DB_PREFIX').'posts.posts_id = '.C('DB_PREFIX').'comment.posts_id')->order('comment_id desc')->limit(C('recent_comments_num'))->findAll();
		foreach ($data as $k=>$v) {
			//$data[$k]['comment_short_content'] = msubstr(htmlspecialchars(addslashes($v['comment_content'])),0,C('recent_comments_limit'));
			$comment_excerpt = preg_replace('/(\r\n)|(\n)/', '', $v['comment_content']); // 消灭换行符
			$comment_excerpt = rc_remove_blockquotes($comment_excerpt); // 消灭所有 blockquote 内容
			$comment_excerpt = preg_replace('/\<(.+?)\>/', '', $comment_excerpt); // 消灭所有标签
			$data[$k]['comment_short_content'] = msubstr($comment_excerpt, 0, C('recent_comments_limit'));
			$data[$k]['comment_ellipsis']  = (strpos($data[$k]['comment_short_content'],"...")) ? 1 : 0 ;
			$data[$k]['comment_email'] = get_gravatar($data[$k]['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
		}
		f_static_cache('comment_static',$data ,$path);
	}
	//日志归档 默认日期对应日志数
	if (!file_exists($path.'posts_static.php')) {
		$posts = M('Posts');
		$map = array();
		$map['posts_status'] = 1; 
		$map['posts_draft'] = 1;
		$map['posts_type'] = 1;
		$data = $posts->where($map)->field('posts_date, count(posts_id) as num')->order('posts_date desc')->group('posts_date')->select();
		$newarr = array();
		foreach ($data as $key => $v) {
				$newarr[$v['posts_date']] = $v['num'];	
		}
		f_static_cache('posts_static',$newarr ,$path);
	}
	//标签
	if (!file_exists($path.'tag_static.php')) {
		$tag  = D('Tag');
		$data = $tag->getTagArray();
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k=='tag_addtime') {
					unset($data[$key][$k]);
				}
			}
		}
		f_static_cache('tag_static',$data ,$path);
	}
	//统计信息
	if (!file_exists($path.'statistics_static.php')) {
		$posts = M('Posts');
		$com   = M('Comment');
		$cat   = M('Category');
		$tag   = M('Tag');
		$tb    = M('Trackback');
		$link  = M('Links');
		//日志
		$posts_map = array();
		$posts_map['posts_status'] = 1; 
		$posts_map['posts_draft'] = 1;
		$posts_map['posts_type'] = 1;
		$posts_num = $posts->where($posts_map)->count();
		//评论
		$comment_sql = '';
		$comment_sql .= ' comment_status = 1 and comment_visible = 1 and comment_type <> 2 ';
		if (C('remark')) {
			$comment_sql .=  ' and comment_remark = 1 ';
		}
		$comment_num = $com->where($comment_sql)->count();
		//留言
		$guestbook_map = array();
		//$guestbook_map['comment_status'] = 1; 
		$guestbook_map['comment_visible'] = 1;
		$guestbook_map['comment_type'] = 2;
		/*if (C('remark')) {
			$comment_map['comment_remark'] = 1;
		}*/
		$guestbook_num = $com->where($guestbook_map)->count();
		//分类
		$category_num = $cat->where('category_isshow = 1')->count();
		//标签
		$tag_num = $tag->count();
		//附件
		$real_list = array();
		$folder = opendir(ROOT_PATH . UPLOAD_DIR);
		while ($file = readdir($folder)) {
			if ((strpos($file,'.doc') || strpos($file,'.pdf') || strpos($file,'.rar') || strpos($file,'.zip'))!== false) {
				$real_list[] = $file;
			}
		}
		$attachment_num = count($real_list);
		//引用通告
		$tb_map = array();
		$tb_map['tb_visible'] = 1;
		$trackback_num = $tb->where($tb_map)->count();
		//访问量
		$today_num = C('today_pv');
		$total_num = C('total_pv');
		$statistics_addtime = gmtime();
		//友情链接
		$link_map = array();
		$link_map['link_status'] = 1; 
		$link_map['link_visible'] = 1;
		$link_num = $link->where($link_map)->count();
		 
		$data = array(
			'posts_num' => !empty($posts_num) ? intval($posts_num) : 0,
			'comment_num' => !empty($comment_num) ? intval($comment_num) : 0,
			'guestbook_num' => !empty($guestbook_num) ? intval($guestbook_num) : 0,
			'category_num' => !empty($category_num) ? intval($category_num) : 0,
			'tag_num' => !empty($tag_num) ? intval($tag_num) : 0,
			'attachment_num' => !empty($attachment_num) ? intval($attachment_num) : 0,
			'trackback_num' => !empty($trackback_num) ? intval($trackback_num) : 0,
			'link_num' => !empty($link_num) ? intval($link_num) : 0,
			'today_num' => !empty($today_num) ? intval($today_num) : 0,
			'total_num' => !empty($total_num) ? intval($total_num) : 0,
			'statistics_addtime' => $statistics_addtime,
		);
		f_static_cache('statistics_static',$data ,$path);
	}
}

/**
 * 获得模版的信息
 *
 * @access  private
 * @param   string    $template_name   模版名
 * @return  array
 */
function get_template_info($template_name) {

    $file_dir =  "./".TEMPLATE_DIR . $template_name;
	$arr = array();
	$info = array();
	
	$ext  = array('png', 'gif', 'jpg', 'jpeg');

    $info['code']       = $template_name;
    $info['screenshot'] = '';

	foreach ($ext as $val) {
		if (file_exists($file_dir . "/screenshot.$val")) {
			$info['screenshot'] = $file_dir . "/screenshot.$val";
		}
	}
	
	if (file_exists($file_dir.'/info.txt') && !empty($template_name)) {
		$arr = @file($file_dir.'/info.txt');

        $template_name_      = explode(': ', $arr[0]);
        $template_uri        = explode(': ', $arr[1]);
        $template_desc       = explode(': ', $arr[2]);
        $template_version    = explode(': ', $arr[3]);
        $template_author     = explode(': ', $arr[4]);
        $template_author_uri = explode(': ', $arr[5]);
		$template_tag        = explode(': ', $arr[6]);

        $info['name']        = isset($template_name[1]) ? trim($template_name_[1]) : '';
        $info['uri']         = isset($template_uri[1]) ? trim($template_uri[1]) : '';
        $info['desc']        = isset($template_desc[1]) ? trim($template_desc[1]) : '';
        $info['version']     = isset($template_version[1]) ? trim($template_version[1]) : '';
        $info['author']      = isset($template_author[1]) ? trim($template_author[1]) : '';
        $info['author_uri']  = isset($template_author_uri[1]) ? trim($template_author_uri[1]) : '';
		$info['tag']         = isset($template_tag[1]) ? trim($template_tag[1]) : '';
        $info['templatedir'] = trim($file_dir);
		
    } else {
        $info['name']        = '';
        $info['uri']         = '';
        $info['desc']        = '';
        $info['version']     = '';
        $info['author']      = '';
        $info['author_uri']  = '';
		$info['tag']         = '';
		$info['templatedir'] = trim($file_dir);
    }
	return $info;
}

/**
 *  获得随机数
 *
 * @access     public
 * @param      string      $n       随机数长度
 * @return     string      $name    随机名称
*/
function get_uid($n) {
	$name = NULL;
	for ($j=0;$j<$n;$j++) {
		srand((double)microtime()*1000000);
		$randname=rand(!$j ? 1: 0,9);
		$name.=$randname;
	}
	return $name;
	$name = NULL;
}

/**
 *  获得随机大小
 *
 * @access     public
 * @param      string      $n       随机数长度
 * @return     array       
*/
function random_size($n) {
    /* 随机显示字体大小 */
    $arr = array('0.8em', '0.9em', '1.0em', '1.1em', '1.2em', '1.3em');
    if ($n > 6) {
        $n = $n % 6;
    }
    return $arr[$n];
}

/**
 * 该函数在插件中调用,挂载插件函数到预留的钩子上
 *
 * @param string $key
 * @param string $value
 * @return boolearn
 */
function add_action($key,$value,$order=10) {
	global $filter;
	$filter[$key][$order]=$value;
}

/**
 * 执行挂在钩子上的函数
 *
 * @param string $key
 */
function do_action($key) {
    global $filter;
    ksort($filter[$key]);
    foreach ($filter[$key] as $function) {
        call_user_func($function);
    } 
}

/**
 * 调用投票内容
 *
 * @access  public
 * @param   integer $id   投票的编号
 * @return  array
 */
function get_vote($id = '') {
	$v  = M('Vote');
	$vo = M('VoteOption');
	$db = M();
    /* 随机取得一个投票的主题 */
    if (empty($id)) {
        $timestamp = gmtime();		
		$vote = $v->field('*,rand() as rnd')->where("vote_visible = 1 AND vote_status = 1 AND
		 vote_starttime <= '$timestamp' AND vote_endtime >= '$timestamp'")->order('rnd desc')->limit(1)->find();	
    } else {
		$vote = $v->where("vote_visible = 1 AND vote_status = 1 AND vote_id = '$id'")->find();
    }

    if ($vote !== false && !empty($vote)) {
         /* 通过投票的ID,查询投票选项 */	 
		$sql_option = 'SELECT v.*, o.* ' . 'FROM ' . C('DB_PREFIX'). 'vote AS v, ' .C('DB_PREFIX') . 'vote_option AS o ' .
                      "WHERE o.vote_id = v.vote_id AND o.vote_id = '$vote[vote_id]' order by option_sort asc";
        $res = $db->query($sql_option);
		/* 总票数 */
		$option_num = $vo->where("vote_id = ".$vote['vote_id'])->sum('option_count');
		
		$arr = array();
        $count = 100;
        foreach ($res as $idx => $row) {
            if ($option_num > 0 && $idx == count($res) - 1) {
                $percent = $count;
            } else {
                $percent = ($row['vote_count'] > 0 && $option_num > 0) ? round(($row['option_count'] / $option_num) * 100) : 0;
                $count -= $percent;
            }
			if($percent < 0) {
				$percent = 0;
			}
            $arr[$row['vote_id']]['options'][$row['option_id']]['percent'] = $percent;
            $arr[$row['vote_id']]['vote_id']       = $row['vote_id'];
            $arr[$row['vote_id']]['vote_name']     = htmlspecialchars(stripslashes($row['vote_name']));
            $arr[$row['vote_id']]['vote_type']     = $row['vote_type'];
			$arr[$row['vote_id']]['vote_filterip'] = $row['vote_filterip'];
			$arr[$row['vote_id']]['vote_view']     = $row['vote_view'];
            $arr[$row['vote_id']]['vote_count']    = $row['vote_count'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_id']    = $row['option_id'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_name']  = $row['option_name'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_url']   = $row['option_url'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_count'] = $row['option_count'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_sort']  = $row['option_sort'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_color'] = get_uid(1); //随机颜色
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] = ($percent == 0) ? 1 : round($percent);//进度条长度
			if($arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] == 100) {
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] = 99;
			}
        }

        $vote['vote_id'] = (!empty($vote['vote_id'])) ? $vote['vote_id'] : '';

        $ret = array('id' => $vote['vote_id'], 'content' => $arr);

        return $ret;
    }
}

/**
 * 分割ip
 */
function split_ip($str) {
	$str = str_replace("\n",",",$str);
	$str = str_replace("\r",",",$str);
	$str = str_replace(",,",",",$str);
	$str = explode(",",$str);
	return $str;
}

function base64_url_encode($input) {
	return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input) {
	return base64_decode(strtr($input, '-_,', '+/='));
}

/**
 * 从$_POST，$_GET，$_COOKIE，$_REQUEST等数组中获得数据
 *
 * @access  public
 * @param   string $text 要处理的字符串
 * @return  string
 */
function get_var(&$string) {
	if (is_string($string) ) {
        $string = Input::getVar($string);
    } elseif (is_array($string)){
        foreach ($string as $key => $val) {
            $string[$key] = get_var($val);
        }
    } elseif (is_object($string)) {
        $vars = get_object_vars($string);
        foreach ($vars as $key => $val) {
            $string->$key = get_var($val);
        }
    }
    return $string;
}

/**
 * 对用户传入的变量进行去除转义操作
 *
 */
/*import("@.ORG.Input");
if (get_magic_quotes_gpc()) {
	$_GET = get_var($_GET);
	$_POST = get_var($_POST);
	$_COOKIE = get_var($_COOKIE);
	$_REQUEST  = get_var($_REQUEST);
}*/

/**
 * 对用户传入的变量进行去除转义操作
 *
 * @access  public
 * @return  void
 */
function all_stripslashes() {
	if (get_magic_quotes_gpc()) {
		$_GET = stripslashes_deep($_GET);
		$_POST = stripslashes_deep($_POST);
		$_COOKIE = stripslashes_deep($_COOKIE);
		$_REQUEST = stripslashes_deep($_REQUEST);
	}
}


/**
 * Remove all blockquote nodes.
 */
function rc_remove_blockquotes($str) {
	$start_pattern = '<blockquote';
	$end_pattern = '</blockquote>';
	// The number of blockquote nodes.
	$quote_count = substr_count(strtolower($str), $start_pattern);
	// If there are 0 blockquote nodes, do nothing.
	if ($quote_count <= 0) {
		return $str;
	// If there is 1 blockquote node, remove it.
	} else if($quote_count == 1) {
		$all_pattern = '/(\<blockquote(.*?)\>)(.*)(\<\/blockquote\>)/i';
		return preg_replace($all_pattern, '', $str);
	}
	// If there are more than 1 backquote nodes, pick the first ending tag.
	$end = strpos(strtolower($str), $end_pattern);
	// Loop all the blockquotes.
	while ($end) {
		// Get substring before first ending tag, and pick the last starting tag.
		$str_before_end = substr($str, 0, $end);
		$start = strrpos(strtolower($str_before_end), $start_pattern);
		// Replace blockquote node to separate.
		$sep = ' ';
		$str = substr_replace($str, $sep, $start, $end + strlen($end_pattern) - $start);
		// Pick next ending tag.
		$end = strpos(strtolower($str), $end_pattern);
	}
	return $str;
}

/**
 * 邮件发送
 *
 * @param: $email[string]       接收人邮件地址
 * @param: $subject[string]     邮件标题
 * @param: $content[string]     邮件内容
 * @param: $type[int]           0 普通邮件， 1 HTML邮件
 *
 * @return boolean
 */
function send_mail($email, $subject, $content, $type = 1) {
    
    /**
     * 使用mail函数发送邮件
     */
    if (C('mail_service') == 0 && function_exists('mail')) {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ? 'Content-Type: text/plain; charset=utf-8' : 'Content-Type: text/html; charset=utf-8';
        $headers = array();
        $headers[] = 'From: "' . '=?UTF8?B?' . base64_encode(C('blog_name')) . '?='.'" <' . C('smtp_mail') . '>';
        $headers[] = $content_type . '; format=flowed';
        $res = @mail($email, '=?UTF8?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers));
        if (!$res) {
		    return false;
        } else {
            return true;
        }
    } else {
		/**
		 * 使用smtp服务发送邮件
		 */
		import('@.ORG.Phpmailer');				
		$mail = new PHPMailer();   
		$mail->IsSMTP();
		$mail->Username = C('smtp_user'); 
		$mail->Password = C('smtp_pass');
		$mail->From     = C('smtp_mail');   
		$mail->Host     = C('smtp_host');
		$mail->Port     = C('smtp_port');
		$mail->Mailer   = "smtp";   
		$mail->FromName = C('blog_name'); 
		($type == 0) ? $mail->IsHTML(false) : $mail->IsHTML(true);
		$mail->SMTPAuth = true;
		$mail->CharSet  = "utf-8";
		$mail->Encoding = "base64";  
		$mail->Subject  = $subject; 
		$mail->AddAddress("$email", "");
		$mail->Body     = $body;		
		if (!$mail->Send()) { 
			return false;  
			continue;  
		} else {
			return true;
		} 
		// Clear all addresses and attachments for next loop   
		$mail->ClearAddresses();   
		$mail->ClearAttachments();
    }
}

?>